// 基本信息
import DialogBox from "@/components/DialogBox";
import { ElForm } from "element-plus";
import { defineComponent, PropType } from "vue";
import LazyUploadFile from "@/components/Upload/LazyUploadFile.vue";
import { serviceMod } from "@/api/modules/service/service";
import { showTips } from "@/utils/util";
interface DeviceForm {
	[key: string]: any;
}
export default defineComponent({
	props: {
		width: String,
		title: String,
		detail: {
			type: Object as PropType<DeviceForm | any>,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { attrs, emit }) {
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const uploadEl = ref();
		const formRule = reactive({
			sn: [{ required: true, message: "请输入网关SN", trigger: "change" }]
		});
		const validData = () => {
			formRef.value?.validate(async valid => {
				if (valid) {
					if (!uploadEl.value || !uploadEl.value.getFile()) {
						saveService();
						return;
					}
					uploadEl.value.submit({ instanceId: `${props.detail.sn}.${props.detail.sn}.SSIOT-MASTER` });
				}
			});
		};
		const saveService = async () => {
			let { code } = await serviceMod({
				instanceId: `${props.detail.sn}.${props.detail.sn}.SSIOT-MASTER`,
				arg: props.detail.arg
			});
			let ok = showTips(code, "更新程序");
			ok && emit("submit");
		};
		const uploadSuccess = async (res: any) => {
			showTips(res.code, "上传", res.message);
			if (res.code == 200) {
				saveService();
			}
		};
		onMounted(() => {});
		return () => {
			return (
				<DialogBox
					{...attrs}
					width={props.width}
					title={props.title}
					onConfirm={() => {
						validData();
					}}
				>
					<el-form model={props.detail} ref={formRef} rules={formRule} label-width="100px">
						<el-form-item label="服务程序" prop="bin">
							<div class="form-item-upload">
								{props.detail.bin ? (
									<div class="file-info ">
										{props.detail.bin}
										<el-link
											type="primary"
											class="delete-server-file ml-2 leading-3"
											onClick={() => {
												uploadEl.value.editFile();
												props.detail.bin = "";
											}}
										>
											重新上传
										</el-link>
									</div>
								) : null}
								<LazyUploadFile
									style={{ display: props.detail.bin ? "none" : "block" }}
									title="点击选择网关程序"
									ref={uploadEl}
									showIcon={false}
									v-model:fileUrl={props.detail.bin}
									v-model:fileName={props.detail.bin}
									onSuccess={uploadSuccess}
									width="150px"
									height="32px"
									emptyTips="请上传网关程序"
								></LazyUploadFile>
							</div>
						</el-form-item>
						<el-form-item label="启动参数" prop="arg">
							<el-input v-model={props.detail.arg} />
						</el-form-item>
					</el-form>
				</DialogBox>
			);
		};
	}
});
